<template>
  <div class="swiper-container" id="mySwiper">
    <div class="swiper-wrapper">
      <div class="swiper-slide" v-for="item in data" :key="item.id">
        <img :src="item.imgUrl" />
      </div>
    </div>
    <!-- 如果需要分页器 -->
    <div class="swiper-pagination"></div>

    <!-- 如果需要导航按钮 -->
    <div class="swiper-button-prev"></div>
    <div class="swiper-button-next"></div>
  </div>
</template>

<script>
import Swiper from 'swiper'
export default {
  name: 'Carousel',
  props: ['data'],
  watch: {
    bannerList: {
      // immediate 立即监听，不管监听的数据是否改变都能监听到
      immediate: true,
      handler(newValue, oldValue) {
        // 由于数据要从vuex里拿，dispatch后经过actions到mutations再到state中修改数据，当页面数据还没拿到时，就已经创建Swiper实例了，因此不能在mounted中实例化Swiper
        // 通过Vue.$nextTick()解决v-for消耗时间的问题，让Swiper实例化在循环遍历后执行
        this.$nextTick(() => {
          // eslint-disable-next-line no-unused-vars
          const mySwiper = new Swiper('.swiper-container', {
            loop: true, // 循环模式选项
            autoplay: {
              delay: 3000
            },
            // 如果需要分页器
            pagination: {
              el: '.swiper-pagination',
              clickable: true
            },

            // 如果需要前进后退按钮
            navigation: {
              nextEl: '.swiper-button-next',
              prevEl: '.swiper-button-prev'
            },

            // 如果需要滚动条
            scrollbar: {
              el: '.swiper-scrollbar'
            }
          })
        })
      }
    }
  }
}
</script>

<style></style>
